//
//  XMSegmentView.m
//  XMKit
//
//  Created by Ce Liu on 2018/5/29.
//  Copyright © 2018年 ChenXiaoMing. All rights reserved.
//

#import "XMSegmentView.h"

@interface XMSegmentView ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *dataSources;

@property (nonatomic, strong) UIView *line;

@property (nonatomic, copy) segmentBlock selectBlock;

@end

static NSString *const cellIdentifier = @"cellIdentifier";

@implementation XMSegmentView

+ (instancetype)segmentTitleViewWithDatas:(NSArray<NSString *> *)datas {
    NSMutableArray *tmpArr = [NSMutableArray arrayWithCapacity:datas.count];
    
    BOOL isDefault = YES;
    for (NSString *str in datas) {
        XMSegmentModel *model = [[XMSegmentModel alloc]init];

        model.title = str;
        
        if (isDefault) {
            model.selected = YES;
            isDefault = NO;
        }
        [tmpArr addObject:model];
    }
    
    XMSegmentView *segment = [[XMSegmentView alloc]init];
    
    segment.dataSources = [NSMutableArray arrayWithArray:tmpArr];
    
    return segment;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor colorWithRed:253/255.0 green:166/255.0 blue:57/255.0 alpha:1.0];
        _selectedColor = [UIColor redColor];
        _normalColor = [UIColor whiteColor];
        _fontSize = 12.0;
        [self.collectionView registerClass:[XMSegmentCell class] forCellWithReuseIdentifier:cellIdentifier];
    }
    
    return self;
}

- (void)reloadData {
    
    [self.collectionView reloadData];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.dataSources.count;
}

- (void)selectedIndexWithBlock:(segmentBlock)block {
    
    _selectBlock = block;
}

- (void)setDatas:(NSArray<NSString *> *)datas {
    _datas = datas;
    NSMutableArray *tmpArr = [NSMutableArray arrayWithCapacity:datas.count];
    
    BOOL isDefault = YES;
    for (NSString *str in datas) {
        XMSegmentModel *model = [[XMSegmentModel alloc]init];
        model.title = str;
        model.fontSize = self.fontSize;
        if (isDefault) {
            model.selected = YES;
            isDefault = NO;
        }
        [tmpArr addObject:model];
    }
    
    self.dataSources = [NSMutableArray arrayWithArray:tmpArr];
}

- (void)setFontSize:(CGFloat)fontSize {
    _fontSize = fontSize;
    if (self.datas.count > 0) {
        for (XMSegmentModel *model in self.datas) {
            model.fontSize = fontSize;
        }
    }
}

- (void)setDataSources:(NSMutableArray *)dataSources {
    _dataSources = dataSources;
    [self.collectionView reloadData];
}

- (void)setSelectedIndex:(NSInteger)selectedIndex animation:(BOOL)animation {
    _selectedIndex = selectedIndex;
    
    NSIndexPath *path = [NSIndexPath indexPathForRow:selectedIndex inSection:0];
    
    [self moveLineToIndexPath:path animation:NO];
    [self.collectionView scrollToItemAtIndexPath:path atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:animation];
    
    for (XMSegmentModel *model in self.dataSources) {
        model.selected = NO;
    }
    
    XMSegmentModel *model = [self.dataSources objectAtIndex:selectedIndex];
    
    model.selected = YES;
    
    [self.collectionView reloadData];
    
}

- (void)setSelectedIndex:(NSInteger)selectedIndex {
    _selectedIndex = selectedIndex;
    [self setSelectedIndex:selectedIndex animation:YES];
}
#pragma mark - Getter
- (UIView *)line {
    if (_line == nil) {
        _line = [[UIView alloc]init];
        _line.backgroundColor = _selectedColor;
        [self.collectionView addSubview:_line];
    }
    
    return _line;
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XMSegmentCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    XMSegmentModel *model = [self.dataSources objectAtIndex:indexPath.row];
    cell.title = model.title;
    cell.isSelected = model.selected;
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath  {
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    [self setSelectedIndex:indexPath.row animation:YES];
    
    // 代理回调
    if (self.delegate && [self.delegate respondsToSelector:@selector(segmentView:didSelectedIndex:)]) {
        [self.delegate segmentView:self didSelectedIndex:indexPath.row];
    }
    // block 回调
    if (self.selectBlock) {
        self.selectBlock(indexPath.row);
    }
}
#pragma mark - UICollectionViewFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    XMSegmentModel *model = [self.dataSources objectAtIndex:indexPath.row];
    return CGSizeMake(model.width, 30);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 4, 0, 4);
}


- (UICollectionView *)collectionView {
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 4;
        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.backgroundColor = self.backgroundColor;
        collectionView.showsVerticalScrollIndicator = NO;
        collectionView.showsHorizontalScrollIndicator = NO;
        [self addSubview:collectionView];
        _collectionView = collectionView;
    }
    
    return _collectionView;
}
- (void)moveLineToIndexPath:(NSIndexPath *)indexPath animation:(BOOL)animation {
    
    XMSegmentCell *cell = (XMSegmentCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    
    CGRect lineBounds = self.line.bounds;
    lineBounds.size.width = cell.bounds.size.width;
    
    CGPoint lineCenter = self.line.center;
    lineCenter.x = cell.center.x;
    
    if (animation) {
        
        [UIView animateWithDuration:0.1 animations:^{
            
            self.line.bounds = lineBounds;
            self.line.center = lineCenter;
        }];
    } else {
        
        self.line.bounds = lineBounds;
        self.line.center = lineCenter;
    }
    
}
#pragma mark - layoutSubviews
- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.collectionView.backgroundColor = self.backgroundColor;
    
    self.collectionView.frame = self.bounds;
    
    XMSegmentModel *model = [self.dataSources firstObject];
    
    self.line.frame = CGRectMake(4, CGRectGetHeight(self.frame) - 2, model.width, 2);
    
    [self setSelectedIndex:self.selectedIndex animation:NO];
}

@end

static CGFloat __fontSize = 12.0;

@interface XMSegmentCell ()

@property (nonatomic, strong) UILabel *titleLabel;

@end

@implementation XMSegmentCell

- (UILabel *)titleLabel {
    if (_titleLabel == nil) {
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont systemFontOfSize:12];
        [self addSubview:_titleLabel];
    }
    
    return _titleLabel;
}
- (void)setTitle:(NSString *)title {
    _title = title;
    
    self.titleLabel.text = title;
}

- (void)setIsSelected:(BOOL)isSelected {
    _isSelected = isSelected;
    
    self.titleLabel.textColor = isSelected ? _selectedColor : _normalColor;
}
- (void)setFontSize:(CGFloat)fontSize {
    _fontSize = fontSize;
    
    self.titleLabel.font = [UIFont systemFontOfSize:fontSize];
    __fontSize = fontSize;
}
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _selectedColor = [UIColor redColor];
        _normalColor = [UIColor whiteColor];
        _fontSize = 12.0;
        self.backgroundColor = [UIColor clearColor];
    }
    
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.titleLabel.backgroundColor = self.backgroundColor;
    
    self.titleLabel.frame = self.bounds;
}

@end

@implementation XMSegmentModel

- (instancetype)init {
    self = [super init];
    if (self) {
        _selected = NO;
        _fontSize = 12.0;
    }
    
    return self;
}

- (CGFloat)width {
    if (_width <= 0) {
        CGFloat wid = [self.title boundingRectWithSize:CGSizeMake(0, 40) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:self.fontSize]} context:nil].size.width;
        
        _width = wid + 10;
    }
    
    return _width;
}

@end
